#include "fileutils.h"
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <string.h>

struct stat st_info;

bool isFile(const char* path)
{
    if (exist(path))
    {
        return S_ISREG(st_info.st_mode);
    }

    return false;
}

bool exist(const char* path)
{
    if (path)
    {
        return (stat(path, &st_info) == 0);
    }

    return false;
}

std::list<std::string> listFiles(const char* path) throw (OpenFileException)
{
    std::list<std::string> result;

    if (isFile(path))
    {   
        result.push_back(path);
        return result;
    }

    DIR* directory = 0;
    struct dirent* entry = 0;

    if ((directory = opendir(path)) == NULL)
    {
        throw OpenFileException(path);
    }

    while ((entry = readdir(directory)))
    {
        bool isNotCurrentOrParentDirectory = strncmp(entry->d_name, "..", 2) != 0 &&
                strncmp(entry->d_name, ".", 1) != 0;

        if (isNotCurrentOrParentDirectory)
        {
            std::string file = entry->d_name;
            result.push_back(file);
        }
    }

    closedir(directory);
}
